import axios, { type AxiosRequestConfig, type AxiosResponse, AxiosError } from 'axios'
import { useAuthStore } from '../stores/auth' // 导入 useAuthStore
import authMgr from './auth'

class HttpRequest {
  private instance: any

  constructor(baseURL: string = '', timeout: number = 5000) {
    this.instance = axios.create({
      baseURL,
      timeout
    })

    // 添加请求拦截器
    this.instance.interceptors.request.use(
      (config: AxiosRequestConfig) => {
        // 获取 authStore 实例
        const { getToken } = useAuthStore()

        const token = getToken() // 从 authStore 中获取 token
        if (token) {
          config.headers.Authorization = `${token}` // 设置 Authorization header
        }
        return config
      },
      (error: AxiosError) => {
        // 对请求错误做些什么
        return Promise.reject(error)
      }
    )

    // 添加响应拦截器
    this.instance.interceptors.response.use(
      (response: AxiosResponse) => {
        const returnCode = response.data.RESPONSE.RETURN_CODE
        // console.log(returnCode, response)

        if (returnCode === 0) {
          return response.data.RESPONSE.RETURN_DATA
        } else {
          if (returnCode == 403) {
            authMgr.logout()
          }
          return Promise.reject(
            new AxiosError(response.data.RETURN_DESC, returnCode, undefined, null, response)
          )
        }
      },
      (error: AxiosError) => {
        // 对响应错误做点什么
        return Promise.reject(error)
      }
    )
  }

  // GET 请求
  get(url: string, params?: any): Promise<any> {
    return new Promise((resolve, reject) => {
      this.instance
        .get(url, { params })
        .then((response: any) => {
          resolve(response)
        })
        .catch((error: any) => {
          reject(error)
        })
    })
  }

  // POST 请求
  post(url: string, data?: any): Promise<any> {
    return new Promise((resolve, reject) => {
      this.instance
        .post(url, data)
        .then((response: any) => {
          resolve(response)
        })
        .catch((error: any) => {
          reject(error)
        })
    })
  }
}

// 创建实例
const http = new HttpRequest('./', 5000)

export default http
